import React, { Component } from "react";
import moment from "moment";

class Calculate extends Component {
  state = {
    data: 0,
  };

  static getDerivedStateFromProps(props) {
    const { getData, form } = props;
    const startkey = getData("start");
    const endkey = getData("end");
    const type = getData("type");
    const operation = getData("operation");
    let start;
    let end;
    switch (type) {
      case "number":
        start = form.getFieldValue(startkey) || 0;
        end = form.getFieldValue(endkey) || 0;
        return {
          data: eval(`${end} ${operation} ${start}`),
        };
      case "date":
        start = form.getFieldValue(startkey) || moment();
        end = form.getFieldValue(endkey) || moment();
        return {
          data: end.diff(start, "days"),
        };
      default:
        return {
          data: 0,
        };
    }
  }

  render() {
    const { getStyle } = this.props;
    const { data } = this.state;
    return <div style={getStyle()}>{data}</div>;
  }
}

export default Calculate;
